<template>
<div class="my-selector">
    <div
    class="selected-value"
    @click = "showOptionsList"
    >
    {{ selectedValue }}
    </div>
    <div class="options-list" v-if="visible">
        <a
        class="list-item"
            href="javascript:;"
          v-for="item of data"
          :key="item.id"
          @click="selectValue(item)"
        >
        {{ item[textKey] }}
        </a>
    </div>

</div>
</template>
<script setup>
import {toRefs,reactive} from 'vue';
// 如果不和父组件产生响应式关系，就直接结构出来

const {
    data,
    textKey,
    defaultValue
} = defineProps({
    data:Object,
    textKey:String,
    defaultValue:String
})
const state = reactive({
    selectedValue:defaultValue || data[0][textKey],
    visible:false
})
const emit = defineEmits(['update'])
const setVisible = (isVisible) =>{
    state.visible = isVisible
}
const showOptionsList=()=>{
    setVisible(!state.visible)
}

const selectValue=(item)=>{
    state.selectedValue = item[textKey]
    setVisible(false)
    emit('update',state.selectedValue)
}
const {
    selectedValue,
    visible
} = toRefs(state)
</script>
<style lang="scss" scoped>
.my-selector{
    width:100%;
    height: 33px;
    border: 1px solid #ddd;
    margin:15px;
    box-sizing: border-box;

    .selector-value{
        height: 100%;
        line-height: 33px;
        text-align: center;
    }
    .options-list{
        display: flex;
        flex-direction: column;
        border:1px solid #ddd;
        border-top:none;
        background-color: #fff;
        margin-top: 1px;
        box-sizing: border-box;
        z-index: 99;

        .list-item{
            display:block;
            height: 33px;
            line-height: 33px;
            text-align: center;
            color:#999;

            &:hover{
                background-color: #ededed;
            }

        }
    }
}
</style>